const fs = require('fs')
const Path = require('path')
const { dialog, ipcMain, shell } = require('electron');

//封装一些常用功能

const fileIsExist = (path) => {
    if (!fs.existsSync(path)) {
        return false;
    }

    return fs.statSync(path).isFile();
}

//删除&重建目录
//自动判断目标路径是文件还是文件夹
const rmAndmkdir = (dirPath) => {
    if (!fs.existsSync(dirPath)) {
        fs.mkdir(dirPath)
        return
    }

    if (fs.statSync(dirPath).isFile()) {
        fs.unlinkSync(dirPath);
    }

    if (fs.statSync(dirPath).isDirectory()) {
        fs.rmSync(dirPath, {
            recursive: true
        });
    }

    fs.mkdirSync(dirPath);
    return true;
}

//根据输出路径 提前建立目录结构
//fs只能自动创建一层，该方法自动递归创建多层
//@param filePath:string  目标路径  可以是指向文件的，可以是指向目录的
const mkdirByPath = (filePath) => {
    const splitSymbol = "\\"

    //先统一路径分隔符
    filePath = filePath.replaceAll("/", "\\");

    const dirs = filePath.split(splitSymbol);
    let cursorPath = "";

    for (let i = 0; i < dirs.length - 1; i++) {
        cursorPath = Path.join(cursorPath, dirs[i]);

        if (!fs.existsSync(cursorPath)) {
            fs.mkdirSync(cursorPath);
        }
    }

    return true;
}

// 获取函数名
// 具名函数的函数名,匿名函数的变量名，闭包返回anonymous
// const getFunctionName = (callee) => {
//     let _callee = callee.toString().replace(/[\s\?]*/g, ""),
//         comb = _callee.length >= 50 ? 50 : _callee.length;

//     _callee = _callee.substring(0, comb);
//     let name = _callee.match(/^function([^\(]+?)\(/);

//     if (name && name[1]) {
//         return name[1];
//     }

//     let caller = callee.caller,
//         _caller = caller.toString().replace(/[\s\?]*/g, "");

//     let last = _caller.indexOf(_callee),
//         str = _caller.substring(last - 30, last);

//     name = str.match(/var([^\=]+?)\=/);

//     if (name && name[1]) {
//         return name[1];
//     }

//     return "anonymous"
// };

/* 打开文件选择对话框*/
// @param title:string         标题
// @param properties: string[] 配置
// @param filters: FileFilter[]文件后缀过滤器
/*
    properties:[
        "openFile",         //目标为文件
        "openDirectory",    //目标为文件夹
        "multiSelections",  //多选
        "showHiddenFiles",  //显示隐藏
    ]

    filters:[
        {
            name:string  过滤名
            extensions:string[]  后缀名
        }
    ]
*/
async function _openDirDialog(title, properties, filters) {
    let rs;

    await dialog.showOpenDialog({
        title,
        filters,
        properties,
        buttonLabel: '打开',
    }).then(result => {
        rs = result;
    });

    return rs;
}

const _openBrowerUrl = (url) => {
    shell.openExternal(url)
}

//打开文件资源管理器，并定位到某个文件
//@param filePath 完整文件路径+文件名称
function _openExplorer(filePath) {
    shell.showItemInFolder(filePath);
}


async function _openConfirmDialog(message, buttons, type) {
    let rs;
    await dialog.showMessageBox({
        title: "",
        message,
        buttons,
        type,
    }).then(result => {
        rs = result
    })
    return rs;
}

const ipcMainInit = () => {

    //打开选择文件对话框
    ipcMain.handle("open-file-dialog", (evnet, title, properties, filters) => {
        return _openDirDialog(title, properties, filters);
    })

    //打开文件资源管理器，并定位到文件
    ipcMain.on("open-explorer", (event, filePath) => {
        _openExplorer(filePath)
    })

    ipcMain.on("open-brower-url", (event, url) => {
        _openBrowerUrl(url)
    })


    //打开确认对话框
    ipcMain.handle("open-confirm-dialog", (evnet, msg, buttons, type) => {
        return _openConfirmDialog(msg, buttons, type);
    })
}

ipcMainInit();

module.exports = {
    fileIsExist,
    rmAndmkdir,
}